package org.example.jwtdemo.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.jwtdemo.entity.User;
import org.example.jwtdemo.service.LoginService;
import org.example.jwtdemo.service.UserService;
import org.example.jwtdemo.utils.Result;
import org.example.jwtdemo.utils.ThreadLocalUtils;
import org.example.jwtdemo.utils.jwtutils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/info")
    public Result userInfo() {
        User user = ThreadLocalUtils.get();
        User userx = userService.getUserInfo(user);
        return Result.success(userx);
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {

        log.info("login user_name: {}", user.getUsername());
        log.info("login password: {}", user.getPassword());
        try {
            User loginuser = loginService.login(user);
            HashMap<String, String> map = new HashMap<>();
            map.put("id", loginuser.getId() + "");//将id和username放入map
            map.put("username", loginuser.getUsername());
            map.put("password", loginuser.getPassword());
            String token = jwtutils.geteToken(map);//获取token

            //验证token
            DecodedJWT verifyToken = jwtutils.verifyToken(token);

            long currentTime = System.currentTimeMillis();
            long exp = verifyToken.getExpiresAt().getTime();
            long remainingMillis = exp - currentTime;

// 转换为天/小时/分钟/秒
            long days = TimeUnit.MILLISECONDS.toDays(remainingMillis);
            long hours = TimeUnit.MILLISECONDS.toHours(remainingMillis) % 24;
            long minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMillis) % 60;
            long seconds = TimeUnit.MILLISECONDS.toSeconds(remainingMillis) % 60;

            System.out.printf("token过期时间：%s\n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(exp)));
            System.out.printf("剩余有效时间：%d天 %d小时 %d分钟 %d秒\n", days, hours, minutes, seconds);

            System.out.println(loginuser.getId());


            //吧token存入redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(String.valueOf(loginuser.getId()), token,1, TimeUnit.HOURS);//把token作为键，token作为值 过期时间为一小时

            //吧token存入redis
//            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
//            operations.set(token, token,1, TimeUnit.MINUTES);//把token作为键，token作为值 过期时间为一小时
            return Result.loginSuccess(token);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @GetMapping("/test")
    public Result test(@RequestHeader("Authorization") String token, HttpServletRequest request) {
        log.info("test token: {}", token);
        //String Authorizaation = request.getHeader("Authorization");
        DecodedJWT verifyToken = jwtutils.verifyToken(token);
        log.info("用户id: {}", verifyToken.getClaim("id").asString());
        log.info("用户名: {}", verifyToken.getClaim("username").asString());
        User userx = ThreadLocalUtils.get();
        System.out.println("ThreadLocal:" + userx);

        return Result.success();
    }
}
